package com.bcx.wind.workflow.imp.cmd.repositorycmd.windprocesscmd;

import com.bcx.wind.workflow.access.QueryFilter;
import com.bcx.wind.workflow.core.constant.ProcessStatus;
import com.bcx.wind.workflow.entity.WindProcess;
import com.bcx.wind.workflow.errorcontext.WindError;
import com.bcx.wind.workflow.interceptor.Command;
import com.bcx.wind.workflow.interceptor.CommandContext;
import com.bcx.wind.workflow.parser.ProcessBuilder;
import com.bcx.wind.workflow.parser.ProcessBuilderFactory;
import com.bcx.wind.workflow.support.Assert;

import java.util.Comparator;
import java.util.List;

import static com.bcx.wind.workflow.message.ErrorCode.PROCESS_QUERY_NULL;

/**
 * 查询最高版本的流程定义
 *
 * @author zhanglei
 */
public class QueryMaxVersionCommand implements Command<WindProcess> {

    /**
     * 流程定义名称
     */
    private String processName;

    public QueryMaxVersionCommand(String processName){
        this.processName = processName;
    }

    @Override
    public WindProcess executor(CommandContext context) {
        try{
            return execute(context);
        }catch (Exception e){
            return null;
        }
    }


    private WindProcess execute(CommandContext context){
        if(this.processName == null){
            WindError.error(PROCESS_QUERY_NULL,null,processName);
        }
        QueryFilter filter = new QueryFilter()
                .setProcessName(this.processName)
                .setStatus(ProcessStatus.RELEASE);
        List<WindProcess> processes = context.access().selectProcessList(filter);
        Assert.notEmptyError(PROCESS_QUERY_NULL,processes,processName);
        WindProcess process = processes.stream().max(Comparator.comparingInt(WindProcess::getVersion))
                .get();

        WindProcess pro  = context.getConfiguration().getProcess(process.getId());
        if(pro == null){
            ProcessBuilder processBuilder = ProcessBuilderFactory.getBuilder(process.getContent());
            processBuilder.buildProcess(process.getId());
            process.processModel(processBuilder.getProcessModel());
            context.getConfiguration().addProcessCache(process);
            return process;
        }
        return pro;
    }
}
